#include "uigtk.hpp"
#include <iostream>

static void *start_pa(void *x);

HelloWorld::HelloWorld() : sing_checkbutton("Sing"),
                           appaudio_checkbutton("App Audio"),
                           m_box(false,10)
{
    set_border_width(10);

    sing_checkbutton.signal_clicked().connect(sigc::mem_fun(*this,&HelloWorld::toggle_sing));
    appaudio_checkbutton.signal_clicked().connect(sigc::mem_fun(*this, &HelloWorld::toggle_appaudio));

    m_box.pack_start(sing_checkbutton,Gtk::PACK_EXPAND_PADDING);
    m_box.pack_start(appaudio_checkbutton, Gtk::PACK_EXPAND_PADDING);

    add(m_box);

    show_all_children();
    setupParty();
}

HelloWorld::~HelloWorld(){

}

void HelloWorld::setupParty(){
    int s = socket(AF_INET, SOCK_DGRAM, 0);
    Receiver *receiver = new Receiver(s);
    Mixer<Trackreceiver> *trackMixer = new Mixer<Trackreceiver>;
    Trackreceiver *musicTrack = new Trackreceiver();
    Trackreceiver *vocalTrack = new Trackreceiver();
    trackMixer->addSource(musicTrack);
    trackMixer->addSource(vocalTrack);
    Channel *music_channel = new Channel(music, channel_unreliable, 1, s, [=](Packet *p)
                                         {
            musicTrack->receiveSound(p);
            return true; });
    Channel *vocal_channel = new Channel(vocal, channel_unreliable, 1, s, [=](Packet *p)
                                         {
            vocalTrack->receiveSound(p);
            return true; });
    receiver->addChannel(music_channel);
    receiver->addChannel(vocal_channel);

    pthread_t pa_thread;
    ci = new struct coreinfo;
    ci->trackMixer = trackMixer;
    ci->musicTrack = musicTrack;
    ci->vocalTrack = vocalTrack;
    ci->musicChannel = music_channel;
    ci->vocalChannel = vocal_channel;
    ci->receiver = receiver;
    pthread_create(&pa_thread, NULL, start_pa, ci);
    receiver->receive_forever();
}

void HelloWorld::toggle_sing(){
    if(sing_checkbutton.get_active()){
        startSinging(ci);
    }else{
        stopSinging(ci);
    }
}

void HelloWorld::toggle_appaudio(){
    if(appaudio_checkbutton.get_active()){
        startAppAudio(ci);
    }else{
        stopAppAudio(ci);
    }

}

int main(int argc, char *argv[]){
    auto app=Gtk::Application::create(argc,argv,"org.ken.wifiparty");
    HelloWorld hw;
    return app->run(hw);
}

static void *start_pa(void *x)
{
    painitialize((coreinfo *)x);
    return nullptr;
}
